const base = require("./base");
const moment = require("moment");
const rankTree = function(arr) {
    arr.sort((a, b) => {
        return (
            moment(a.created_at).format("X") - moment(b.created_at).format("X")
        );
    });
    arr.map(val => {
        if (val.sub && val.sub.length) {
            return rankTree(val.sub);
        } else {
            return val;
        }
    });

    return arr;
};
module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
        await super.isUserAuth();
    }

    /**
     *
     * @api {post}/comment/api/api/addComment 对商品进行评论
     * @apiDescription 对商品进行评论
     * @apiGroup comment api
     * @apiVersion 0.0.1
     *
     * @apiParam {int}  id  订单id
     * @apiSampleRequest /comment/api/api/addComment
     *
     */
    // 只有已完成的订单才能进行评价
    async addComment() {
        const { id, content, star, type = "putong" } = this.post;
        const shop_id = this.state.shop.id;
        const user_id = this.state.user.id;
        const model = type === "putong" ? "order" : "shop_order_pintuan";
        let commentArr = "";
        const addData =
            type === "putong"
                ? {
                      id: id,
                      status: 3
                  }
                : {
                      id: id,
                      order_status: 3
                  };
        const orderInfo = await this.model(model)
            .query(qb => {
                qb.where("id", "=", id);
                qb.where("status", "=", 2);
            })
            .fetch({
                withRelated: type === "putong" ? ["detail"] : []
            });

        if (!orderInfo) {
            this.fail("订单不能进行评价，请审核订单");
            return;
        }

        // 生成评价订单
        if (type === "putong") {
            commentArr = orderInfo.detail.map((item, index) => {
                const row = {
                    order_id: item.order_id,
                    shop_id: shop_id,
                    user_id: user_id,
                    product_id: item.product_id,
                    content: content,
                    star: star,
                    type: 0,
                    pid: 0,
                    status: 1
                };
                return row;
            });
        } else {
            commentArr = [
                {
                    order_id: orderInfo.id,
                    shop_id: shop_id,
                    user_id: user_id,
                    product_id: orderInfo.product_id,
                    content: content,
                    star: star,
                    type: 0,
                    pid: 0,
                    status: 1,
                    from_type: 1
                }
            ];
        }

        // 保存到 shop_order_comment 表中
        await doodoo.bookshelf.Collection.extend({
            model: doodoo.model("order_comment")
        })
            .forge(commentArr)
            .invokeThen("save");

        // 改变订单状态

        await this.model(model)
            .forge(addData)
            .save();

        this.success("订单评论成功");
    }

    /**
     *
     * @api {post}/comment/api/api/commentAgain 对评论进行回复
     * @apiDescription 对评论进行回复
     * @apiGroup comment api
     * @apiVersion 0.0.1
     *
     * @apiParam {int}  id  订单id
     * @apiSampleRequest /comment/api/api/commentAgain
     *
     */
    // 暂时支持 自己回复自己的评论

    async commentAgain() {
        const { id = 0, content = "" } = this.post;
        const user_id = this.state.user.id;
        const commentInfo = await this.model("order_comment")
            .query(qb => {
                qb.where("id", "=", id);
            })
            .fetch();
        const data = {
            pid:
                Number(commentInfo.pid) === 0
                    ? commentInfo.id
                    : commentInfo.pid,
            user_id: user_id,
            reply_id: commentInfo.user_id,
            content: content,
            type: 0,
            order_id: commentInfo.order_id,
            shop_id: commentInfo.shop_id,
            product_id: commentInfo.product_id
        };
        try {
            await this.model("order_comment")
                .forge(data)
                .save();
        } catch (err) {
            console.log("err-->", err);
        }

        this.success("评论成功");
    }

    /**
     *
     * @api {get}/comment/api/api/listComment 商品的评论列表
     * @apiDescription 商品的评论列表
     * @apiGroup comment api
     * @apiVersion 0.0.1
     *
     * @apiParam {int}  id  商品id
     * @apiParam {int}  type  是否显示全部评论 all 全部 ，not all 非全部
     * @apiSampleRequest /comment/api/api/listComment
     *
     */

    async listComment() {
        const { id = 0, type = "all" } = this.query;
        const shop_id = this.state.shop.id;
        let [sum, goods] = [0, 0];
        const list = await this.model("order_comment")
            .query(qb => {
                qb.where("shop_id", "=", shop_id);
                qb.where("product_id", "=", id);
                qb.where("status", "=", 1);
                if (type === "not all") {
                    qb.limit(2);
                }
            })
            .fetchAll({
                withRelated: [
                    "user",
                    "subComment",
                    {
                        subComment: qb => {
                            qb.where("type", 1);
                        }
                    }
                ]
            });

        const treeComment = rankTree(this.getTree(list));

        // 计算好评率

        for (let x = 0; x < list.length; x++) {
            if (Number(list[x].pid) === 0) {
                sum += 1;
                if (list[x].star >= 4) {
                    goods += 1;
                }
            }
        }

        this.success({
            list: treeComment,
            rate: (goods / sum * 100).toFixed(2)
        });
    }
};
